#include <iostream>
#include <memory>
#include <string>
#include <stdio.h>

#include "Udp_Server.hpp"
using namespace std;

//客户端的数据cmd
string ExcuteCommand(const string& cmd)
{
    FILE* fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    
    string result;
    char buffer[4096];
    while(true)
    {
        //获取客户端的数据
        char* ok = fgets(buffer, sizeof(buffer), fp);
        if(ok == nullptr) break;
        result += buffer;
    }
    pclose(fp);

    return result;
}

void Usage(string proc)
{
    cout << "\n\rUsage:" << proc << "serverip serverport\n" << endl;
}

//服务端接收到客户端的端口号, ip地址随机.
// ./udpserver port
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = stoi(argv[1]);

    unique_ptr<UdpServer> svr(new UdpServer(port));
    svr->Init();
    svr->Run(ExcuteCommand);
    return 0;
}